package controllers;

import helpers.CountryHelper;
import helpers.HeaderHelper;
import helpers.ItuneXMLUrlHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;

import crawlers.CrawlerItuneXML;
import debug.SoftwareDebug;

import models.Country;
import models.FeedType;
import models.Genre;
import models.Software;


public class Home extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		
		response.setHeader("Cache-Control", "public, max-age=86400");
		response.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		
		response.setCharacterEncoding("UTF-8");
		//Set header page
		HeaderHelper headerHelper = new HeaderHelper();
		
		//Set variable
		ArrayList<Software> softwares = new ArrayList<Software>();
		ArrayList<Country> countries = (ArrayList<Country>) CountryHelper.getCountries();
		//Obtain the session object, create a new session if doesn't exist
        HttpSession session = request.getSession(true);
        
		//Set country feed type, size and 
		ItuneXMLUrlHelper ituneUrlHepler = new ItuneXMLUrlHelper();
		ArrayList<FeedType> types = ituneUrlHepler.getTypes();
		ArrayList<Genre> genres = ituneUrlHepler.getGenres();
		ArrayList<String> limits = ituneUrlHepler.getLimits();
		
		String country = (String) request.getParameter("country");
		String type = (String) request.getParameter("type");
		String limit = (String) request.getParameter("limit");
		String genre = (String) request.getParameter("genre");
		
		ItuneXMLUrlHelper urlHelper = new ItuneXMLUrlHelper();
		if (country != null) {
			urlHelper.setCountry(country);
		} else {
			if (session.getAttribute("country") != null) {
				urlHelper.setCountry((String) session.getAttribute("country"));
			} else {
				try {
					if (CountryHelper.checkExistsCountry(request.getHeader("X-AppEngine-country"))) {
						urlHelper.setCountry(request.getHeader("X-AppEngine-country").toLowerCase());
					}
				} catch (Exception e) {
					urlHelper.setCountry("vn");
				}
				
			}
		}
		
		if (type != null) {
			urlHelper.setType(type);
		} else {
			if (session.getAttribute("feedType") != null) {
				urlHelper.setType((String) session.getAttribute("feedType"));
			}
		}

		if (limit != null) {
			urlHelper.setLimit(limit);
		} else {
			if (session.getAttribute("limit") != null) {
				urlHelper.setLimit((String) session.getAttribute("limit"));
			}
		}
		
		if (genre != null && !genre.equalsIgnoreCase("0")) {
			urlHelper.setGenreId(genre);
		} else {
			urlHelper.setGenreId("0");
		}
		
        session.setAttribute("country", urlHelper.getCountry());
        session.setAttribute("feedType", urlHelper.getType() );
        session.setAttribute("limit", urlHelper.getLimit());
        session.setAttribute("genre", urlHelper.getGenreId());
		
        //Set cache
        Cache cache=null;
        String cachename = "topapps_" + urlHelper.getCountry() + "_" + urlHelper.getType() + "_" + urlHelper.getLimit() + "_" + urlHelper.getGenreId();
        try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
        System.out.println(cachename);
        if (cache.containsKey(cachename)) {
        	softwares = (ArrayList<Software>) cache.get(cachename);
        	System.out.println("softwares: cache print");
        } else {
        	softwares = (ArrayList<Software>) CrawlerItuneXML.getXML(urlHelper.getUrl());
        	if (softwares.size() > 0) {
        		cache.put(cachename, softwares);
        	}
	        System.out.println("softwares: Data print");
        }
        
        //Set header
        FeedType feedType = (FeedType) urlHelper.getTypeByAlias(urlHelper.getType());
        headerHelper.setTitle(feedType.getName() + " (" + urlHelper.getLimit() + " apps) in " + urlHelper.getCountry());
        headerHelper.setOgtitle(feedType.getName() + " (" + urlHelper.getLimit() + " apps) in " + CountryHelper.getCountryByCode(urlHelper.getCountry()).getName() );
        
		/*SoftwareDebug.debug(softwares.get(0));*/
		request.setAttribute("headerHelper", headerHelper);
		request.setAttribute("softwares", softwares);
		request.setAttribute("countries", countries);
		request.setAttribute("types", types);
		request.setAttribute("genres", genres);
		request.setAttribute("limits", limits);
		request.setAttribute("country", urlHelper.getCountry());
		request.setAttribute("type", urlHelper.getType());
		request.setAttribute("genre", urlHelper.getGenreId());
		request.setAttribute("limit", urlHelper.getLimit());
		try {
			request.getRequestDispatcher("/pages/homepage.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
